go http examples

87 阅读1分钟

快速开始

package main
 
import (
    "fmt"
    "net/http"
)
 
func main() {
    // handle route using handler function
    http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
        fmt.Fprintf(w, "Welcome to new server!")
    })
 
    // listen to port
    http.ListenAndServe(":5050", nil)
}

多个路由

package main
 
import (
    "fmt"
    "net/http"
)
 
func main() {
    http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
        fmt.Fprintf(w, "Welcome to new server!")
    })
 
    http.HandleFunc("/students", func(w http.ResponseWriter, r *http.Request) {
        fmt.Fprintf(w, "Welcome Students!")
    })
 
    http.HandleFunc("/teachers", func(w http.ResponseWriter, r *http.Request) {
        fmt.Fprintf(w, "Welcome teachers!")
    })
 
    http.ListenAndServe(":5050", nil)
}

自定义Mux

package main
 
import (
    "io"
    "net/http"
)
 
func welcome(w http.ResponseWriter, r *http.Request) {
    io.WriteString(w, "Welcome!")
}
 
func main() {
 
    mux := http.NewServeMux()
 
    mux.HandleFunc("/welcome", welcome)
    
    // 其实性能上没有区别,不传入的话,会使用默认的Mux
    http.ListenAndServe(":5050", mux)
}

自定义响应Header和状态码

w.WriteHeader(200) 是修改该响应码,不是修改响应头

package main

import (
	"net/http"
)

func main() {
	http.HandleFunc("/", func (w http.ResponseWriter, r *http.Request) {
		// alter header first
		w.Header().Add("hello","world")
		// and then the response code
		w.WriteHeader(200)
		w.Write([]byte("hello world"))
	})

	http.ListenAndServe(":8080", nil)
}
  • 测试:
        [root@localhost awesomeProject]# curl -i localhost:8080
	HTTP/1.1 200 OK
	Hello: world
	Date: Sat, 10 Dec 2022 06:38:40 GMT
	Content-Length: 11
	Content-Type: text/plain; charset=utf-8

	hello world