Golang面试题目汇总与解析
Golang面试题目汇总与解析 谁能提示一些关于Go面试问题的资源?特别是Web开发相关的问题?
3 回复
我在快速谷歌搜索后找到了几篇文章。不过,我没找到太多专门关于 Go 语言 Web 开发的内容。
希望这些能帮到你!
Go 语言开发者顶级面试问题
事情是这样的,我面试过很多人,反过来,我自己也喜欢去其他公司参加面试。
阅读时间:5 分钟
https://career.guru99.com/top-20-go-programming-interview-questions/
全栈开发者面试问题 ☕ FullStack.Café
FullStack.Café 帮助开发者攻克技术面试,获得他们心仪的工作。
以下是一些常见的Go语言Web开发面试题目及解析,包含示例代码:
1. Goroutine与Channel
问题:解释Goroutine和Channel的区别,并展示如何用Channel实现Goroutine同步。
解析:
- Goroutine是轻量级线程,Channel用于Goroutine间通信。
- 示例:使用Channel等待Goroutine完成。
package main
import "fmt"
func worker(done chan bool) {
fmt.Println("working...")
done <- true // 发送完成信号
}
func main() {
done := make(chan bool, 1)
go worker(done)
<-done // 等待接收信号
fmt.Println("done")
}
2. Context包的使用
问题:如何在Web请求中正确使用Context处理超时?
解析:
- Context用于传递请求截止时间、取消信号。
- 示例:设置请求超时。
package main
import (
"context"
"fmt"
"time"
)
func handleRequest(ctx context.Context) {
select {
case <-time.After(2 * time.Second):
fmt.Println("request processed")
case <-ctx.Done():
fmt.Println("request cancelled:", ctx.Err())
}
}
func main() {
ctx, cancel := context.WithTimeout(context.Background(), 1*time.Second)
defer cancel()
go handleRequest(ctx)
time.Sleep(2 * time.Second)
}
3. HTTP服务器
问题:如何创建一个基本的HTTP服务器并处理路由?
解析:
- 使用
net/http包创建服务器,http.HandleFunc注册路由。 - 示例:创建带路由的服务器。
package main
import (
"fmt"
"net/http"
)
func helloHandler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hello, World!")
}
func main() {
http.HandleFunc("/hello", helloHandler)
http.ListenAndServe(":8080", nil)
}
4. 中间件实现
问题:如何实现一个记录请求耗时的中间件?
解析:
- 中间件是包装HTTP处理函数的函数。
- 示例:记录请求处理时间。
package main
import (
"fmt"
"net/http"
"time"
)
func loggingMiddleware(next http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
start := time.Now()
next(w, r)
fmt.Printf("Request took %v\n", time.Since(start))
}
}
func helloHandler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hello!")
}
func main() {
http.HandleFunc("/hello", loggingMiddleware(helloHandler))
http.ListenAndServe(":8080", nil)
}
5. 数据库操作
问题:如何使用database/sql包连接和查询PostgreSQL数据库?
解析:
- 导入数据库驱动,使用
sql.Open连接,Query执行查询。 - 示例:查询用户数据。
package main
import (
"database/sql"
"fmt"
_ "github.com/lib/pq"
)
func main() {
connStr := "user=postgres dbname=test sslmode=disable"
db, err := sql.Open("postgres", connStr)
if err != nil {
panic(err)
}
defer db.Close()
rows, err := db.Query("SELECT id, name FROM users")
if err != nil {
panic(err)
}
defer rows.Close()
for rows.Next() {
var id int
var name string
rows.Scan(&id, &name)
fmt.Println(id, name)
}
}
6. JSON处理
问题:如何将结构体序列化为JSON并返回HTTP响应?
解析:
- 使用
encoding/json包的Marshal函数。 - 示例:返回JSON响应。
package main
import (
"encoding/json"
"net/http"
)
type User struct {
ID int `json:"id"`
Name string `json:"name"`
}
func getUser(w http.ResponseWriter, r *http.Request) {
user := User{ID: 1, Name: "Alice"}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(user)
}
func main() {
http.HandleFunc("/user", getUser)
http.ListenAndServe(":8080", nil)
}
7. 错误处理
问题:在Go Web应用中如何统一处理错误?
解析:
- 自定义错误类型,中间件捕获panic。
- 示例:统一错误处理中间件。
package main
import (
"net/http"
)
func errorMiddleware(next http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
defer func() {
if err := recover(); err != nil {
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
}
}()
next(w, r)
}
}
func panicHandler(w http.ResponseWriter, r *http.Request) {
panic("something went wrong")
}
func main() {
http.HandleFunc("/panic", errorMiddleware(panicHandler))
http.ListenAndServe(":8080", nil)
}
8. 测试
问题:如何对HTTP处理函数进行单元测试?
解析:
- 使用
net/http/httptest包模拟请求和响应。 - 示例:测试
/hello路由。
package main
import (
"net/http"
"net/http/httptest"
"testing"
)
func TestHelloHandler(t *testing.T) {
req := httptest.NewRequest("GET", "/hello", nil)
w := httptest.NewRecorder()
helloHandler(w, req)
if w.Code != http.StatusOK {
t.Errorf("expected status 200, got %d", w.Code)
}
if w.Body.String() != "Hello, World!" {
t.Errorf("unexpected body: %s", w.Body.String())
}
}
这些题目涵盖了Go Web开发的核心概念,包括并发、HTTP处理、数据库和测试。

