Skip to content

Commit

Permalink
basic_auth & readme
Browse files Browse the repository at this point in the history
  • Loading branch information
fritx committed Aug 11, 2024
1 parent e37d25a commit 8f3a1d8
Show file tree
Hide file tree
Showing 6 changed files with 196 additions and 5 deletions.
16 changes: 16 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
# we-mid/go

> Go util/SDK 合集
代码仓库:

- Gitee:https://gitee.com/we-mid/go
- GitHub:https://github.com/we-mid/go

文件目录:

- [basic_auth](./basic_auth):HTTP Basic-Auth 辅助函数库
- [bd_fanyi](./bd_fanyi):简单易用的 百度翻译 SDK
- [tc_sms](./tc_sms):简单易用的 腾讯云SMS短信发送 SDK
- [util](./util)
- ...更多
44 changes: 44 additions & 0 deletions basic_auth/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
# basic_auth

> HTTP Basic-Auth 辅助函数库
```ini
# .env
BASICAUTH_USERLIST='[{"user":"xxx","pass":"xxxxxx"},{"user":"xxx","pass":"xxxxxx"}]'
```

```go
import (
// ...
"gitee.com/we-mid/go/basic_auth"
"gitee.com/we-mid/go/util"
)

func init() {
if err := basic_auth.InitFromEnv(); err != nil {
log.Fatalln("basic_auth.InitFromEnv:", err)
}
}

func main() {
// API路由
http.HandleFunc("/api/foo", util.HandlerWrap(apiFoo))
http.HandleFunc("/api/bar", util.HandlerWrap(apiBar))
// 页面路由,创建一个文件服务器
fs := http.FileServer(http.Dir("./public"))
http.HandleFunc("/", basic_auth.Wrap(func(w http.ResponseWriter, r *http.Request) {
fs.ServeHTTP(w, r)
}))
// ...
}

func apiFoo(w http.ResponseWriter, r *http.Request) error {
if err := util.EnableCors(w, r); err != nil {
return err
}
if user := basic_auth.Check(r); user == "" {
return util.Err401
}
// ...
}
```
58 changes: 58 additions & 0 deletions basic_auth/basic_auth.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
package basic_auth

import (
"encoding/json"
"net/http"
"os"
)

type HandlerFunc func(http.ResponseWriter, *http.Request)

type User struct {
Username string `json:"user"`
Password string `json:"pass"`
}

var (
userMap = map[string]User{}
)

func AddUser(user User) {
userMap[user.Username] = user
}

func InitFromEnv() error {
var list []User
JSON := os.Getenv("BASICAUTH_USERLIST")
if err := json.Unmarshal([]byte(JSON), &list); err != nil {
return err
}
for _, user := range list {
AddUser(user)
}
return nil
}

func Wrap(next HandlerFunc) HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
user := Check(r)
if user == "" { // reject
w.Header().Set("WWW-Authenticate", `Basic realm="Restricted"`)
http.Error(w, "Unauthorized.", http.StatusUnauthorized)
return
}
next(w, r) // pass
}
}

func Check(r *http.Request) string {
username, password, ok := r.BasicAuth()
if ok {
if user, ok := userMap[username]; ok {
if password == user.Password {
return username
}
}
}
return ""
}
3 changes: 3 additions & 0 deletions basic_auth/go.mod
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
module gitee.com/we-mid/go/basic_auth

go 1.21.1
62 changes: 62 additions & 0 deletions bd_fanyi/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
# bd_fanyi

> 简单易用的 百度翻译 SDK
```ini
# .env
BAIDUFANYI_APP_ID=xxxxxxxx
BAIDUFANYI_APP_SECRET=xxxxxxxx
```

```go
import "gitee.com/we-mid/go/bd_fanyi"

func init() {
bd_fanyi.InitFromEnv()
}

func handleFanyi(w http.ResponseWriter, r *http.Request) (any, error) {
defer r.Body.Close()
// ...
var req bd_fanyi.FanyiReq
if err := json.NewDecoder(r.Body).Decode(&req); err!=nil {
return nil, fmt.Errorf("json.Decode: %w", err)
}
bd_fanyi.CompleteReq(&req)
// list: []*bd_fanyi.TranslateResult
list, err := client.Translate(&req)
if err != nil {
return nil, fmt.Errorf("client.Translate: %w", err)
}
return list, nil
}
```

```go
// bd_fanyi.FanyiReq:
type FanyiReq struct {
Text string `json:"text"`
From baidufanyi.Language `json:"from"`
To baidufanyi.Language `json:"to"`
}
// bd_fanyi.Language = baidufanyi.Language:
// https://github.com/chyroc/baidufanyi/blob/master/language.go
LanguageEn Language = "en" //
LanguageCht Language = "cht" // 中文(繁体)
LanguageWyw Language = "wyw" // 中文(文言文)
LanguageYue Language = "yue" // 中文(粤语)
LanguageZh Language = "zh" // 中文(简体)

// bd_fanyi.TranslateResult = baidufanyi.TranslateResult:
// https://github.com/chyroc/baidufanyi/blob/master/translate.go
type TranslateResult struct {
Src string `json:"src"`
Dst string `json:"dst"`
}
```

### 参考链接

- 通用翻译API接入文档:https://fanyi-api.baidu.com/doc/21
- 通用翻译API版本权益调整通知(计费标准):https://fanyi-api.baidu.com/doc/8
- 本SDK基于/二次封装了baidufanyi:https://github.com/chyroc/baidufanyi
18 changes: 13 additions & 5 deletions bd_fanyi/fanyi.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,14 +12,22 @@ import (

// 通用翻译API版本权益调整通知
// https://fanyi-api.baidu.com/doc/8
// 标准版 QPS=1 持28个语种互译 单次最长请求1000字符 免费调用量5万字符/月
// 标准版 QPS=1 持28个语种互译 单次最长请求1000字符 免费调用量5万字符/月
// 高级版 QPS=10 支持 28个语种互译 单次最长请求6000字符 免费调用量100万字符/月
// 尊享版 QPS=100 支持200+语种互译 单次最长请求6000字符 免费调用量200万字符/月
var (
appid = os.Getenv("BAIDUFANYI_APP_ID")
secret = os.Getenv("BAIDUFANYI_APP_SECRET")
// 2. 若每月调用量超过免费调用量限制,将按照49元/百万字符进行计费;
// 3. 字符数以翻译的源语言字符长度为标准计算。空格、html标签等均计入字符。一个汉字,英文字母,标点符号等,均按照一个字符计费。
var client *bf.Fanyi

func InitFromEnv() {
appid := os.Getenv("BAIDUFANYI_APP_ID")
secret := os.Getenv("BAIDUFANYI_APP_SECRET")
client = bf.New(bf.WithCredential(appid, secret))
)
}

// alias
type TranslateResult = bf.TranslateResult
type Language = bf.Language

type FanyiReq struct {
Text string `json:"text"`
Expand Down

0 comments on commit 8f3a1d8

Please sign in to comment.