package main import ( "fmt" "html/template" "log" "net/http" "strings" ) func login(w http.ResponseWriter, r *http.Request) { fmt.Println("method:", r.Method) if r.Method == "GET" { t, err := template.ParseFiles("H:\\Goproject\\src\\web\\login.html") if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } if err := t.Execute(w, nil); err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) } } else { _ = r.ParseForm() fmt.Println("username:", r.Form["username"]) fmt.Println("password:", r.Form["password"]) if pwd := r.Form.Get("password"); pwd == "123456" { fmt.Fprintf(w, "欢迎登陆,Hello %s!", r.Form.Get("username")) } else { fmt.Fprintf(w, "密码错误!") } } } func sayHello(w http.ResponseWriter, r *http.Request) { _ = r.ParseForm() //3 解析参数,默认不解析 fmt.Println(r.Form) //4 输出到服务器端的打印信息 fmt.Println("Path:", r.URL.Path) for k, v := range r.Form { fmt.Println("key:", k) fmt.Println("value", strings.Join(v, "")) } fmt.Fprintf(w, "Hello aoho") //5 写入到w的是输出到客户端的内容 } func main() { http.HandleFunc("/", login) http.HandleFunc("/sayHello", sayHello) //1 设置访问的路由 err := http.ListenAndServe(":8080", nil) //2 设置监听的端口 if err != nil { log.Fatal("ListenSever:", err) } } 修改为绝对路径可以运行,但是如何修改为相对路径
时间: 2023-07-21 15:12:00 浏览: 93
要将路径修改为相对路径,您需要使用`http.Dir`函数将文件夹路径转换为`http.FileServer`类型。这样可以指定要提供给用户的静态文件所在的文件夹。以下是对代码的修改:
```go
package main
import (
"fmt"
"html/template"
"log"
"net/http"
"strings"
)
func login(w http.ResponseWriter, r *http.Request) {
fmt.Println("method:", r.Method)
if r.Method == "GET" {
t, err := template.ParseFiles("login.html")
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
if err := t.Execute(w, nil); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
} else {
_ = r.ParseForm()
fmt.Println("username:", r.Form["username"])
fmt.Println("password:", r.Form["password"])
if pwd := r.Form.Get("password"); pwd == "123456" {
fmt.Fprintf(w, "欢迎登陆,Hello %s!", r.Form.Get("username"))
} else {
fmt.Fprintf(w, "密码错误!")
}
}
}
func sayHello(w http.ResponseWriter, r *http.Request) {
_ = r.ParseForm() //3 解析参数,默认不解析
fmt.Println(r.Form) //4 输出到服务器端的打印信息
fmt.Println("Path:", r.URL.Path)
for k, v := range r.Form {
fmt.Println("key:", k)
fmt.Println("value", strings.Join(v, ""))
}
fmt.Fprintf(w, "Hello aoho") //5 写入到w的是输出到客户端的内容
}
func main() {
http.HandleFunc("/", login)
http.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir("static"))))
http.HandleFunc("/sayHello", sayHello) //1 设置访问的路由
err := http.ListenAndServe(":8080", nil) //2 设置监听的端口
if err != nil {
log.Fatal("ListenSever:", err)
}
}
```
这里假设您的静态资源文件夹名为`static`,并且在同一级目录下。使用`http.Handle`和`http.StripPrefix`函数来处理静态文件路由,并指定静态文件夹的相对路径。修改后,您应该能够使用相对路径来访问静态文件。
阅读全文