HTTP服务设置保护路由

5年以前  |  阅读数:502 次  |  编程语言:Golang 
package main

import "net/http"
import "fmt"

func hello(res http.ResponseWriter, req *http.Request) {
    res.Header().Set("Content-Type", "text/plain")
    if req.URL.Path == "/protected" {
        res.WriteHeader(401)
        fmt.Fprintln(res, "Not allowed")
    } else {
        fmt.Fprintln(res, "Hello")
    }
}

func main() {
    http.HandleFunc("/", hello)
    http.ListenAndServe(":5000", nil)
}

执行程序:

$ go run xx-http-server-status-code.go
$ curl -i http://127.0.0.1:5000/ | grep HTTP
$ curl -i http://127.0.0.1:5000/protected | grep HTTP

Copyright© 2013-2020

All Rights Reserved 京ICP备2023019179号-8