Lập trình

Go redirect location

Code

package main

import (
    "log"
    "net/http"
)

func redirectHome(w http.ResponseWriter, r *http.Request) {

    http.Redirect(w, r, "/", 301)
}

func main() {
    http.HandleFunc("/", redirectHome)
    err := http.ListenAndServe(":8123", nil)
    if err != nil {
        log.Fatal("ListenAndServe: ", err)
    }
}

Test CURL output

$ curl -v localhost:8123
* Rebuilt URL to: localhost:8123/
*   Trying 127.0.0.1...
* TCP_NODELAY set
* Connected to localhost (127.0.0.1) port 8123 (#0)
> GET / HTTP/1.1
> Host: localhost:8123
> User-Agent: curl/7.54.0
> Accept: */*
>
< HTTP/1.1 301 Moved Permanently
< Content-Type: text/html; charset=utf-8
< Location: /
< Date: Wed, 05 Feb 2020 07:20:54 GMT
< Content-Length: 36
<
<a href="/">Moved Permanently</a>.

* Connection #0 to host localhost left intact

---

Phuc Tran Hoang


Các bài viết khác

Go redirect location
Phuc Tran Hoang