How to build a website in golang

angryTom
Release: 2020-02-15 10:42:57
Original
2364 people have browsed it

How to build a website in golang

How to build a website in golang

Go language provides a complete net/http package, through http The package can easily build a web service that can be run.

At the same time, using this package can easily set up and operate web routing, static files, templates, cookies and other data

.

Related recommendations: golang tutorial

http package to create a web server

1. Server

server.go
package main
import (
    "fmt"
    "net/http"
    "strings"
    "log"
)
func sayhelloName(w http.ResponseWriter, r *http.Request) {
        r.ParseForm() //解析参数,默认是不会解析的
        fmt.Println(r.Form) //这些信息是输出到服务器端的打印信息
        fmt.Println("path", r.URL.Path)
        fmt.Println("scheme", r.URL.Scheme)
        fmt.Println(r.Form["url_long"])
        for k, v := range r.Form {
            fmt.Println("key:", k)
            fmt.Println("val:", strings.Join(v, ""))
        }
        fmt.Fprintf(w, "Hello go web server") //这个写入到w的是输出到客户端的
}
func main() {
        http.HandleFunc("/", sayhelloName) //设置访问的路由
        err := http.ListenAndServe(":9090", nil) //设置监听的端口
        if err != nil {
        log.Fatal("ListenAndServe: ", err)
    }
}
Copy after login

2. Compile and generate executable file

go build server.go
Copy after login

3. Execute

./server
Copy after login

How to build a website in golang

How to build a website in golang

The above is the detailed content of How to build a website in golang. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact [email protected]
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!