LoginSignup
1
1

More than 5 years have passed since last update.

Go言語でフォルダ内のhtmlファイルにメタタグを追加するコマンドラインツールを作る

Posted at

やりたいこと

  • バイナリファイルと同じフォルダ内にあるhtmlファイルすべてに特定のメタタグを追加したい。
  • コマンドラインツールを使えない人に使ってもらう予定なので、実行するだけでいいようにしたい

実際のコード

package main

import (
    "fmt"
    "io/ioutil"
    "os"
    "regexp"
    "strings"
    "path"
)

type FileInfos []os.FileInfo
type ByName struct{ FileInfos }

func main() {
    var arg string

    dir := path.Dir(os.Args[0])
    fmt.Println(dir)
    os.Chdir(dir)

    // カレントディレクトリの取得
    var curDir, _ = os.Getwd()
    curDir += "/"
    arg = curDir




    // ディレクトリ内のファイル情報の読み込み[] *os.FileInfoが返る。
    fileInfos, err := ioutil.ReadDir(arg)

    // ディレクトリの読み込みに失敗したらエラーで終了
    if err != nil {
        fmt.Errorf("Directory cannot read %s\n", err)
        os.Exit(1)
    }

    htmlFiles := regexp.MustCompile("(.*).htm")

    // ファイル情報を一つずつ表示する
    for _, fileInfo := range fileInfos {
        var findName = (fileInfo).Name()
        findhtmlFiles := htmlFiles.FindAllString(findName, -1)
        if len(findhtmlFiles) > 0 {
            contents, err := ioutil.ReadFile((fileInfo).Name())
            fmt.Println(findhtmlFiles)
            if err != nil {
                panic(err)
            }

            content := strings.Replace(string(contents), "<meta http", "<meta name=\"viewport\" content=\"width=device-width\"><meta http", 1)
            fmt.Println(content)

            err = ioutil.WriteFile((fileInfo).Name(), []byte(content), 0644)
            if err != nil {
                panic(err)
            }

        }

    }
}

未解決事項

  • go runで走らせるとtmpフォルダで実行することになるので、毎回buildが必要になる。
  • もっと綺麗に書きたい。。。

参考

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1