Golang 转生到web世界

Golang

因为对於web比较熟的关系,还是希望使用golang来做点web相关的事情,如果是写php的朋友,在一开始都需要安装apache来跑php,但如果是使用golang的话,我们就可以省略这个步骤,直接来玩看看

Golang本身就包含net/http 套件,只需要在import引用就可以,但要注意的是,如果先前都是使用golang online来练习的朋友,可能就需要先安装golang了,尤其後面还需要建置view html档案等,这部分就是线上编辑器无法支援的。

依照惯例直接来看个hello world吧!

package main

import (
	"fmt"
	"net/http"
)

func indexHandler(w http.ResponseWriter, r *http.Request) {
	fmt.Fprintf(w, "hello world")
}

func main() {
	http.HandleFunc("/", indexHandler)
	http.ListenAndServe(":8000", nil)
}

然後跑一下专案 go run 之後在浏览器中输入http://localhost:8000/
这里的ListenAndServe,我写8000是使用8000port,想改什麽数字的就自行改变,但唯一要注意程序码与网址的数字要相同,以及有些常用的port号可能会被别的软件之类使用(apache会遇到这种问题,但golang会不会我不确定,但目前个人猜测应该是不会受影响)。

就可以看到hello world罗
所以真的不用安装apache

如果我们要抓路由怎麽做呢?

package main

import (
	"fmt"
	"net/http"
)

func indexHandler(w http.ResponseWriter, r *http.Request) {
	fmt.Fprintf(w, "Hello, world!\n")
}

func echoHandler(w http.ResponseWriter, r *http.Request) {
	fmt.Fprintf(w, r.URL.Path)
}

func main() {
	mux := http.NewServeMux()
	mux.HandleFunc("/hello", indexHandler)
	mux.HandleFunc("/", echoHandler)

	http.ListenAndServe(":8000", mux)
}

参考资料
https://pkg.go.dev/net/http


<<:  DAY7 浅扒网路 - 估计被扒皮的是我不是网路

>>:  个人管理 - 工作细节拆分

[Day16] JavaScript - Promise 物件

我们过去在写 JavaScript 使用的同步延迟,通常都是用非同步的 setTimeout 加 ...

Day 23: Jenkins与分散式部属

Jenkins可以采用分散式架构,也就是包含Master与Slave的Jenkins,如下图。在部属...

第 8 集:Gird System 格线系统

此篇会简单介绍格线系统原理以及使用技巧。 Bootstrap5 格线系统是基於 flex,想活用格线...

前端工程学习日记第4天

#使用 margin(向外)、padding(向内) 来推挤距离 css: .box{border:...

Day 27:专案07 - 天气小助理01 | 气象资料API

图片来源:https://www.epochtimes.com/b5/18/1/5/n100268...