Skip to content

Instantly share code, notes, and snippets.

@dhirabayashi
Last active April 10, 2023 19:38
Show Gist options
  • Select an option

  • Save dhirabayashi/2671b05dc34b1f4cb071068f28a828dc to your computer and use it in GitHub Desktop.

Select an option

Save dhirabayashi/2671b05dc34b1f4cb071068f28a828dc to your computer and use it in GitHub Desktop.
package main
import (
"fmt"
"io/ioutil"
"log"
"os"
"path/filepath"
"regexp"
)
var pattern *regexp.Regexp
var files = []string{}
func main() {
if len(os.Args) <= 2 {
fmt.Println("[USAGE] atumeru (pattern) (target)")
return
}
patternStr := os.Args[1]
target := os.Args[2]
cudir, _ := os.Getwd()
pattern = regexp.MustCompile(patternStr)
searchFiles(target)
for _, path := range files {
fmt.Println("Copy:" + path)
bname := filepath.Base(path)
savepath := filepath.Join(cudir, bname)
copyFile(path, savepath)
}
}
func searchFiles(target string) {
fs, err := ioutil.ReadDir(target)
if err != nil {
log.Fatal(err)
}
for _, file := range fs {
fpath := filepath.Join(target, file.Name())
if file.IsDir() {
searchFiles(fpath)
continue
}
if pattern.MatchString(file.Name()) {
files = append(files, fpath)
}
}
}
func copyFile(infile, outfile string) bool {
b, err := ioutil.ReadFile(infile)
if err != nil {
return false
}
err = ioutil.WriteFile(outfile, b, 0644)
if err != nil {
return false
}
return true
}
package main
import (
"encoding/json"
"fmt"
"html"
"io/ioutil"
"net/http"
"time"
)
const logFile = "logs.json"
type Log struct {
ID int `json:"id"`
Name string `json:"name"`
Body string `json:"body"`
CTime int64 `json:"ctime"`
}
func main() {
println("server - http://localhost:8888")
http.HandleFunc("/", showHandler)
http.HandleFunc("/write", writeHandler)
http.ListenAndServe(":8888", nil)
}
func showHandler(w http.ResponseWriter, r *http.Request) {
htmlLog := ""
logs := loadLogs()
for _, i := range logs {
htmlLog += fmt.Sprintf(
"<p>(%d) <span>%s</span>: %s --- %s</p>",
i.ID,
html.EscapeString(i.Name),
html.EscapeString(i.Body),
time.Unix(i.CTime, 0).Format("2006/1/2 15:04"))
}
htmlBody := "<html><head><style>" +
"p { border: 1px solid silver; padding: 1em;} " +
"span { background-color: #eef; } " +
"</style></head><body><h1>BBS</h1>" +
getForm() + htmlLog + "</body></html>"
w.Write([]byte(htmlBody))
}
func writeHandler(w http.ResponseWriter, r *http.Request) {
r.ParseForm()
var log Log
log.Name = r.Form["name"][0]
log.Body = r.Form["body"][0]
if log.Name == "" {
log.Name = "名無し"
}
logs := loadLogs()
log.ID = len(logs) + 1
log.CTime = time.Now().Unix()
logs = append(logs, log)
saveLogs(logs)
http.Redirect(w, r, "/", 302)
}
func getForm() string {
return "<div><form action='/write' method='POST'>" +
"名前: <input type='text' name='name'><br>" +
"本文: <input type='text' name='body' style='width:30em;'><br>" +
"<input type='submit' value='書込'>" +
"</form></div><hr>"
}
func loadLogs() []Log {
text, err := ioutil.ReadFile(logFile)
if err != nil {
return make([]Log, 0)
}
var logs []Log
json.Unmarshal([]byte(text), &logs)
return logs
}
func saveLogs(logs []Log) {
bytes, _ := json.Marshal(logs)
ioutil.WriteFile(logFile, bytes, 0644)
}
package main
import (
"fmt"
"math"
)
const weight = 60
const height = 165
func main() {
var hm = height / 100.0
var bmi = weight / math.Pow(hm, 2)
var bestW = math.Pow(hm, 2) * 22.0
var per = weight / bestW * 100
fmt.Printf("BMI=%f, 肥満度=%.0f\n", bmi, per)
}
package main
import (
"io/ioutil"
)
func main() {
infile := "aa.txt"
outfile := "bb.txt"
b, err := ioutil.ReadFile(infile)
if err != nil {
panic(err)
}
err = ioutil.WriteFile(outfile, b, 0644)
if err != nil {
panic(err)
}
}
package main
import (
"fmt"
"math/rand"
"net/http"
)
func main() {
http.HandleFunc("/", DiceHandler)
http.ListenAndServe(":8888", nil)
}
func DiceHandler(w http.ResponseWriter, r *http.Request) {
v := rand.Intn(6) + 1
s := fmt.Sprintf("サイコロの目は、%d", v)
w.Write([]byte(s))
}
package main
import (
"fmt"
"math/rand"
"net/http"
)
func main() {
fs := http.FileServer(http.Dir("pub"))
http.Handle("/", fs)
http.HandleFunc("/dice", DiceHandler)
http.ListenAndServe(":8888", nil)
}
// DiceHandler サイコロHandler
func DiceHandler(w http.ResponseWriter, r *http.Request) {
w.Write([]byte(fmt.Sprintf("<h1>サイコロ: %d</h1>", rand.Intn(6)+1)))
}
package main
import (
"fmt"
"io/ioutil"
"log"
)
func main() {
files, err := ioutil.ReadDir(".")
if err != nil {
log.Fatal(err)
}
for _, file := range files {
fmt.Println(file.Name())
}
}
package main
import (
"fmt"
"io/ioutil"
"log"
"path/filepath"
)
func main() {
for _, f := range GetFiles(".") {
fmt.Println(f)
}
}
func GetFiles(dir string) []string {
var result []string
files, err := ioutil.ReadDir(dir)
if err != nil {
log.Fatal(err)
}
for _, file := range files {
fpath := filepath.Join(dir, file.Name())
if file.IsDir() {
result = append(result, GetFiles(fpath)...)
continue
}
result = append(result, fpath)
}
return result
}
package main
import (
"fmt"
"path/filepath"
)
func main() {
files, _ := filepath.Glob("*")
for i, name := range files {
fmt.Println(i, "=", name)
}
}
package main
import "fmt"
func main() {
fmt.Println("hello, world!")
}
package main
import "net/http"
func main() {
http.HandleFunc("/", HelloHandler)
http.ListenAndServe(":8888", nil)
}
func HelloHandler(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("Hello, World!"))
}
package main
import (
"fmt"
"html"
"io/ioutil"
"net/http"
)
const saveFile = "memo.txt"
func main() {
print("memo server - [URL] http://localhost:8888/\n")
http.HandleFunc("/", readHandler)
http.HandleFunc("/w", writeHandler)
http.ListenAndServe(":8888", nil)
}
func readHandler(w http.ResponseWriter, r *http.Request) {
text, err := ioutil.ReadFile(saveFile)
if err != nil {
text = []byte("ここにメモを記入してください。")
}
htmlText := html.EscapeString(string(text))
s := "<html>" +
"<style>textarea { width:99%; height:200px; }</style>" +
"<form method='POST' action='/w'>" +
"<textarea name='text'>" + htmlText + "</textarea>" +
"<input type='submit' value='保存' /></form></html>"
w.Write([]byte(s))
}
func writeHandler(w http.ResponseWriter, r *http.Request) {
r.ParseForm()
if len(r.Form["text"]) == 0 {
w.Write([]byte("フォームから投稿してください。"))
return
}
text := r.Form["text"][0]
ioutil.WriteFile(saveFile, []byte(text), 0644)
fmt.Println("save: " + text)
http.Redirect(w, r, "/", 301)
}
%{
// プログラムのヘッダを指定
package main
import (
"os"
"fmt"
)
%}
%union {
num int
}
// プログラムの構成要素を指定
%type<num> program expr
%token<num> NUMBER
// 演算の優先度の指定
%left '+','-'
%left '*','/'
%%
// 文法規則を指定
program
: expr
{
$$ = $1
yylex.(*Lexer).result = $$
}
expr
: NUMBER
| expr '+' expr { $$ = $1 + $3 }
| expr '-' expr { $$ = $1 - $3 }
| expr '*' expr { $$ = $1 * $3 }
| expr '/' expr { $$ = $1 / $3 }
%%
// 最低限必要な構造体を定義
type Lexer struct {
src string
index int
result int
}
// ここでトークン(最小限の要素)を一つずつ返す
func (p *Lexer) Lex(lval *yySymType) int {
for p.index < len(p.src) {
c := p.src[p.index]
p.index++
if c == '+' { return int(c) }
if c == '-' { return int(c) }
if c == '*' { return int(c) }
if c == '/' { return int(c) }
if '0' <= c && c <= '9' {
lval.num = int(c - '0')
return NUMBER
}
}
return -1
}
// エラー報告用
func (p *Lexer) Error(e string) {
fmt.Println("[error] " + e)
}
// メイン関数
func main() {
if len(os.Args) <= 1 { return }
lexer := &Lexer{src: os.Args[1], index:0}
yyParse(lexer)
println("計算結果:", lexer.result)
}
package main
import (
"fmt"
"io/ioutil"
"net/http"
)
func main() {
http.HandleFunc("/", indexHandler)
http.HandleFunc("/upload", uploadHandler)
http.ListenAndServe(":8888", nil)
}
func indexHandler(w http.ResponseWriter, r *http.Request) {
s := "<html><body>" +
"<h1>ファイルを指定してください</h1>" +
"<form action='/upload' method='post' " +
" enctype='multipart/form-data'>" +
"<input type='file' name='upfile'>" +
"<input type='submit' value='アップロード'>" +
"</form></body></html>"
w.Write([]byte(s))
}
func uploadHandler(w http.ResponseWriter, r *http.Request) {
file, _, err := r.FormFile("upfile")
if err != nil {
w.Write([]byte("アップロードエラー"))
return
}
data, err := ioutil.ReadAll(file)
if err != nil {
w.Write([]byte("アップロードエラー"))
return
}
s := getBinStr(data)
w.Write([]byte("<html><body>" + s +
"</body></html>"))
}
func getBinStr(bytes []byte) string {
result := "<style>" +
"th { background-color: #f0f0f0; } " +
".c { background-color: #fff0f0; } " +
"td { border-bottom: 1px solid silver } " +
"</style><table>"
line := "<tr>"
aline := ""
cnt := 2
for i := 0; i < len(bytes); i++ {
b := bytes[i]
c := string(b)
if b < 32 || b > 126 {
c = "_"
}
if c == ">" {
c = "&gt;"
}
if c == "<" {
c = "&lt;"
}
aline += c
m := i % 16
if m == 0 {
line += fmt.Sprintf("<th>%04d:</th><td>", i)
}
line += fmt.Sprintf("%02x", b)
switch m {
case 3, 7, 11:
line += "</td><td>"
cnt = -1
case 15:
result += line + "</td>"
result += "<td class='c'>" + aline + "</td></tr>\n"
line = "<tr>"
aline = ""
cnt = 2
default:
line += " "
}
}
if line != "" {
result += line
for j := 0; j < cnt; j++ {
result += "</td><td>"
}
result += "</td><td class='c'>" + aline + "</td></tr>"
}
result += "</table>"
return result
}
package main
import (
"fmt"
"os"
)
func printFile(filename string) {
fp, err := os.Open(filename)
if err != nil {
panic(err)
}
buf := make([]byte, 1)
for {
cnt, _ := fp.Read(buf)
if cnt == 0 {
break
}
fmt.Printf("[%d]", buf[0])
}
}
func main() {
printFile("test.txt")
fmt.Println()
}
package main
import (
"fmt"
"io/ioutil"
)
func printFile(filename string) {
bytes, err := ioutil.ReadFile(filename)
if err != nil {
panic(err)
}
line := ""
aline := ""
for i := 0; i < len(bytes); i++ {
b := bytes[i]
c := string(b)
if b < 32 || b > 126 {
c = "_"
}
aline += c
m := i % 16
if m == 0 {
line += fmt.Sprintf("%04d: ", i)
}
line += fmt.Sprintf("%02x", b)
switch m {
case 7:
line += "|"
case 15:
fmt.Println(line + "|" + aline)
line = ""
aline = ""
default:
line += " "
}
}
if line != "" {
fmt.Printf("%-53s|%s\n", line, aline)
}
}
func main() {
printFile("test.txt")
}
package main
import (
"fmt"
"io/ioutil"
"path/filepath"
"strings"
)
func main() {
files, _ := filepath.Glob("*.html")
for _, fname := range files {
fileReplare(fname, "[email protected]", "[email protected]")
}
}
func fileReplare(fname, src, dst string) {
bytes, _ := ioutil.ReadFile(fname)
lines := strings.Replace(string(bytes), src, dst, -1)
result := []byte(lines)
ioutil.WriteFile(fname, []byte(result), 0666)
fmt.Println("ok: ", fname)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment